<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="./t3.css" />
    <script src="https://cdn.bootcdn.net/ajax/libs/dayjs/1.4.1/dayjs.min.js"></script>
    <title>Document</title>
  </head>
  <body>
    <div class="calendar" id="calendar">
      <div class="calendar-title-box" id="title">
        <select id="year"></select>
        <select id="month"></select>
        <span class="month" id="select-month">月</span>
        <span class="year" id="select-year">年</span>
      </div>
      <div class="show-year" id="show-year">
        <table>
          <tr>
            <td><p>1月</p></td>
            <td><p>2月</p></td>
            <td><p>3月</p></td>
          </tr>
          <tr>
            <td><p>4月</p></td>
            <td><p>5月</p></td>
            <td><p>6月</p></td>
          </tr>
          <tr>
            <td><p>7月</p></td>
            <td><p>8月</p></td>
            <td class="now-month current-month"><p>9月</p></td>
          </tr>
          <tr>
            <td><p>10月</p></td>
            <td><p>11月</p></td>
            <td><p>12月</p></td>
          </tr>
        </table>
      </div>
    </div>
    <script>
      // html结构
      function renderHtml() {
        var calendar = document.getElementById("calendar");
        // 表格区域
        var bodyBox = document.createElement("div");
        bodyBox.className = "calender-body-box";
        // 星期html
        var headHtml = `<tr>
          <th>一</th>
          <th>二</th>
          <th>三</th>
          <th>四</th>
          <th>五</th>
          <th>六</th>
          <th>日</th>
        </tr>`;
        // 日期html
        var bodyHtml = "";
        // 6行7列
        for (var i = 0; i < 6; i++) {
          bodyHtml += `<tr>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
          </tr>`;
        }
        bodyBox.innerHTML = `<table id='calendarTable' class='calendar-table'${headHtml}${bodyHtml}</table>`;
        calendar.appendChild(bodyBox);
      }
      // 头部数据
      function showCalendarTitle() {
        var oyear = document.getElementById("year");
        var omonth = document.getElementById("month");
        // 插入年份
        for (var i = 2015; i <= 2025; i++) {
          var iyear = document.createElement("option");
          iyear.innerHTML = i + "年";
          iyear.value = i;
          // 获取当前年份
          if (i == dayjs().year()) {
            iyear.selected = "selected";
          }
          oyear.appendChild(iyear);
        }
        // 插入月份
        for (var i = 1; i <= 12; i++) {
          var imonth = document.createElement("option");
          imonth.innerHTML = i + "月";
          imonth.value = i;
          if (i == dayjs().month() + 1) {
            imonth.selected = "selected";
          }
          omonth.appendChild(imonth);
        }
        // 绑定查询数据，年月变化触发
        var selectYear = document.getElementById("year");
        var selectMonth = document.getElementById("month");
        selectYear.onchange = function (event) {
          let e = event.target.nodeName.toLowerCase();
          // console.log(e);
          if (e == "select") {
            //获取data属性 找到当前选中的日期
            var currentDay = document.querySelectorAll(".currentDay");
            var data = currentDay[0].getAttribute("data");
            var showday = data.substr(6);
            // console.log(showday);
            query();
            // 遍历更改后的日历，找到对应的日期添加class
            let currentMonths = document.querySelectorAll(".currentMonth");
            // console.log(currentMonths);
            currentMonths.forEach((e) => {
              // console.log(e);
              if (e.getAttribute("data").substr(6) == showday) {
                e.className = "currentDay";
              }
            });
          }
        };
        // 更改月份 选中的日期不变
        selectMonth.onchange = function (event) {
          let e = event.target.nodeName.toLowerCase();
          // console.log(e);
          if (e == "select") {
            //获取data属性 找到当前选中的日期
            var currentDay = document.querySelectorAll(".currentDay");
            var data = currentDay[0].getAttribute("data");
            var showday = data.substr(6);
            // console.log(showday);
            query();
            // 遍历更改后的日历，找到对应的日期添加class
            let currentMonths = document.querySelectorAll(".currentMonth");
            // console.log(currentMonths);
            currentMonths.forEach((e) => {
              // console.log(e);
              if (e.getAttribute("data").substr(6) == showday) {
                e.className = "currentDay";
              }
            });
          }
        };
      }
      // 渲染html
      renderHtml();
      // 渲染头部
      showCalendarTitle();
      // 添加数据
      query();
      // 查询数据 往表格添加号数
      function query() {
        var oyear = document.getElementById("year");
        var omonth = document.getElementById("month");
        // 获取当前日期
        var year = oyear.value;
        var month = omonth.value;
        // console.log(year, month);
        // 表格
        var table = document.getElementById("calendarTable");
        // 所有td元素
        var tds = table.getElementsByTagName("td");
        var nowDate = new Date(year, month - 1, 1);
        // 第一天
        var firstDay = nowDate.getDay();
        var firstDate = nowDate.getDate();
        // 如果第一天为0 则改为星期日
        if (firstDay == 0) {
          firstDay = 7;
        }
        // console.log(firstDay.getDate());
        for (var i = 0; i < tds.length; i++) {
          // 确定第一天的位置
          var thisDay = new Date(year, month - 1, i + firstDate - firstDay + 1);
          // console.log(thisDay);
          // dayjs库转换日期格式年-月-日
          var thisDayStr = dayjs(thisDay).format("YYYYMMDD");
          // console.log(thisDayStr);
          // 获取号数
          var d = thisDay.getDate();
          // console.log(d);
          // 小于9的前面补齐0
          d = d > 9 ? "" + d : "0" + d;
          // 赋值号数
          tds[i].innerHTML = `<p>${d}</p>`;
          tds[i].setAttribute("data", thisDayStr);
          if (thisDayStr == dayjs().format("YYYYMMDD")) {
            // 选中当前天数添加className
            tds[i].className = "currentDay currentMonth now-day";
          } else if (
            thisDayStr.substr(0, 6) == dayjs(nowDate).format("YYYYMM")
          ) {
            // 选中当前月数添加className
            tds[i].className = "currentMonth";
          } else {
            // 其他月的日期
            tds[i].className = "otherMonth";
          }
        }
      }

      // 年月的切换
      var showBox = document.querySelector(".calender-body-box");
      var showYear = document.getElementById("show-year");
      var yearBtn = document.getElementById("select-year");
      var monthBtn = document.getElementById("select-month");
      var month = document.getElementById("month");
      yearBtn.onclick = function () {
        yearBtn.style.border = "1px solid #1890ff";
        yearBtn.style.color = "#1890ff";
        monthBtn.style.border = "1px solid gray";
        monthBtn.style.color = "black";
        showBox.style.display = "none";
        showYear.style.display = "block";
        month.style.display = "none";
      };
      monthBtn.onclick = function () {
        monthBtn.style.border = "1px solid #1890ff";
        monthBtn.style.color = "#1890ff";
        yearBtn.style.border = "1px solid gray";
        yearBtn.style.color = "black";
        showBox.style.display = "flex";
        showYear.style.display = "none";
        month.style.display = "block";
      };
      // 点击选中号数添加背景色
      var tds = document.querySelectorAll(".currentMonth");
      tds.forEach((e) => {
        // console.log(e);
        e.onclick = function () {
          var currentDay = document.querySelectorAll(".currentDay");
          // console.log(currentDay);
          for (let day of currentDay) {
            day.classList.remove("currentDay");
            day.classList.add("currentMonth");
          }
          if (e.getAttribute("class").substr(13) == "now-day") {
            e.className = "currentDay now-day";
          } else {
            e.className = "currentDay";
          }
        };
      });
      // 点击月数添加背景颜色
      var mshowyear = document.getElementById("show-year");
      var myear = document.getElementById("year");
      var mtds = mshowyear.getElementsByTagName("td");
      // console.log(myear);
      myear.onchange = function (event) {
        event.target.onclick = query();
      };
      for (let j = 0; j < mtds.length; j++) {
        // console.log(mtds[j]);
        mtds[j].onclick = function () {
          let currentMonth = mshowyear.getElementsByClassName("current-month");
          currentMonth[0].classList.remove("current-month");
          mtds[j].classList.add("current-month");
          var month = document.getElementById("month");
          var selecemonth = month.getElementsByTagName("option");
          // console.log(selecemonth);
          for (let i = 0; i < selecemonth.length; i++) {
            console.log(selecemonth[i].textContent);
            if (
              selecemonth[i].textContent.substr(0, 2) ==
              mtds[j].textContent.substr(0, 2)
            ) {
              selecemonth[i].selected = "selected";
              query();
            }
          }
          // console.log(mtds[j].textContent);
        };
      }
    </script>
  </body>
</html>
